import { defineStore } from 'pinia'

import { GitUpdateParam, UserUpdateParam, User } from '@/types'
import { LS_USER } from '@/constant/local-storage-key.ts'
import { localStorageGetItem, localStorageSetItem } from '@/utils/local-storage-util.ts'
import { useRouter } from 'vue-router'
import { computed, ref } from 'vue'

const storeSetup = () => {
  const user = ref<User | undefined>(localStorageGetItem(LS_USER))
  const userId = computed(() => user.value?.id)
  const username = computed(() => user.value?.username)
  const email = computed(() => user.value?.email)
  const phone = computed(() => user.value?.phone)
  const realName = computed(() => user.value?.realName)
  const nickname = computed(() => user.value?.nickname)
  const gitee = computed(() => user.value?.gitee)
  const github = computed(() => user.value?.github)
  const description = computed(() => user.value?.description)
  const location = computed(() => user.value?.location)
  const blogName = computed(() => user.value?.blogName)
  const blogDescription = computed(() => user.value?.blogDescription)
  const avatar = computed(() => user.value?.avatar)
  const avatarUrl = computed(() => '/api/file/' + avatar.value)
  const birthday = computed(() => user.value?.birthday)
  const saveLocalStorage = () => {
    localStorageSetItem(LS_USER, user.value)
  }
  const handleSetUser = (val: User) => {
    user.value = val
    saveLocalStorage()
  }

  const handleSetAvatar = (val: string) => {
    if (user.value) {
      user.value.avatar = val
    }
    saveLocalStorage()
  }
  const handleSetUserInfo = (val: UserUpdateParam) => {
    if (user.value) {
      user.value.nickname = val.nickname
      user.value.realName = val.realName
      user.value.birthday = val.birthday
      user.value.email = val.email
      user.value.phone = val.phone
      user.value.description = val.description
      user.value.location = val.location
      user.value.blogName = val.blogName
      user.value.blogDescription = val.blogDescription
    }
    saveLocalStorage()
  }
  const handleSetGit = (val: GitUpdateParam) => {
    if (user.value) {
      user.value.gitee = val.gitee
      user.value.github = val.github
    }
    saveLocalStorage()
  }

  const checkUser = () => {
    if (!user.value) {
      const router = useRouter()
      if (router.currentRoute.value.fullPath !== '/login') {
        router
          .push('/login')
          .then(() => {
            console.log('用户信息丢失，重新登录')
          })
          .catch(error => {
            console.log('跳转异常：', error)
          })
      }
    }
  }

  checkUser()
  return {
    user,
    userId,
    username,
    email,
    phone,
    realName,
    nickname,
    gitee,
    github,
    description,
    location,
    blogName,
    blogDescription,
    avatar,
    avatarUrl,
    birthday,
    handleSetUser,
    handleSetAvatar,
    handleSetUserInfo,
    handleSetGit,
  }
}

export const useUserStore = defineStore('user', storeSetup)
